# -*- coding: utf-8 -*-
from typing import List
from fastapi import Depends
from sqlalchemy.orm import Session
from .service import create_conversation_log, get_conversation_logs
from config.database import get_db
from common.auth import validate_authorization
from common.response import BaseResponse
from pydantic import BaseModel, Field
from conversation_log import conversation_router
from config.logger import logging

# 获取日志记录器
logger = logging.getLogger(__name__)


class ConversationLogResponse(BaseModel):
    id: int
    question: str
    response: str
    thinking: str
    user_id: str  

    class Config:
        from_attributes = True


class ConversationLogRequest(BaseModel):
    question: str = Field(..., min_length=1, max_length=500)
    response: str = Field(..., min_length=0, max_length=20000)
    thinking: str = Field(..., min_length=0, max_length=20000)
    user_id: str = Field(..., min_length=1, max_length=50)
    keyword: str = Field(..., min_length=0, max_length=50)
    is_builtin: int = Field(..., ge=0, le=1)


@conversation_router.post("/add", response_model=BaseResponse[ConversationLogResponse])
def log_conversation(request: ConversationLogRequest, db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    try:
        conversation_log = create_conversation_log(db, question=request.question, thinking=request.thinking, response=request.response, user_id=request.user_id, keyword=request.keyword, is_builtin=request.is_builtin)
        # 修改：返回对象需要符合模型结构
        return BaseResponse(code=200, data=conversation_log, message="Conversation logged successfully")
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return BaseResponse(code=500, data=None, message="Internal Server Error")


@conversation_router.get("/list", response_model=BaseResponse[List[ConversationLogResponse]])
def read_conversation_logs(user_id: str, skip: int = 0, limit: int = 100, db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    try:
        conversation_logs = get_conversation_logs(db, user_id=user_id, skip=skip, limit=limit)
        # 修改：返回列表需要包装在 data 字段
        return BaseResponse(code=200, data=conversation_logs, message="Success")
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return BaseResponse(code=500, data=None, message="Internal Server Error")


